<template>
  <div class="loginbox">
    <!-- 遮罩层 -->
  <div class="mask" @click="changeIsShowLoginModal(false)"></div>
  <!-- 登录的盒子 -->
  <div class="login">
    <div class="close" @click="changeIsShowLoginModal(false)">
    </div>
<section>
    <a href="javascript:;" :class="{active:isShowLogin}" @click="isShowLogin=true">手机号码登录</a> |
    <a href="javascript:;" :class="{active:!isShowLogin}" @click="showQrFn">微信扫码登录</a>
</section>
<div class="content">
    <div class="phonelogin" v-show="isShowLogin">
  <div class="row">
    <input type="text" placeholder="请输入手机号码" v-model="phoneNumber">
  </div> 
  <div class="row">
 <slide-verify :l="42" :r="23" :w="350" :h="138" @success="onSuccess" @fail="onFail" @refresh="onRefresh" :style="{ width: '100%' }" class="slide-box" ref="slideBlock" :slider-text="msg"  :imgs='imgarr' :accuracy=10></slide-verify>
  </div> 
  <div class="row">
    <input type="text" placeholder="请输入短信验证码" v-model="dxcode">
    <button class="btn btncode" @click="getCode" v-show="!isShowCount">获取验证码</button> 
    <button class="btn btncode" v-show="isShowCount">{{count}}s</button>
  </div> 
  <div class="row">
    <button class="btn btnlogin" @click="submitFn">登录</button>
  </div>
    </div>
    <div class="qrlogin" id="weixin" v-show="!isShowLogin">
    </div>
</div>
    </div>
  </div>
</template>

<script>
import {mapActions, mapMutations,mapState} from "vuex"
import {validatePhoneNumber} from "@/utils"
import {SendSMSAPI,PhoneReginAPI,BindingAPI,UserProfilesAPI} from "@/request/api.js"
export default {
    data(){
return{
    isShowLogin:true,
      msg: "向右滑动",
      imgarr:[
        require("../assets/img/integral-01.9386d4bf.png"), require("../assets/img/integral-02.150d92a1.png"),
        require("../assets/img/integral-03.9870f3f1.png"), require("../assets/img/integral-04.afadcbdf.png"),
        ],
        phoneNumber:"",
        count:6,
        isShowCount:false,
        dxcode:"",
}
    },
methods:{
    ...mapMutations({
        changeIsShowLoginModal:"showModal/changeIsShowLoginModal",
        changeIsLogined:"loginStatus/changeIsLogined",
    }),
    ...mapActions({
         asyncShowToast:"showToast/asyncShowToast",
         asyncChangeUserInfo:"userInfo/asyncChangeUserInfo",
    }),
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "login success, 耗时 " + ms + "s";
    },
    // 拼图失败
    onFail() {
      this.onRefresh(); // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = "再试一次";
    },
    // 校验手机号码格式和滑块验证码
        toVerify(){
        // 校验手机号码格式
        if(!validatePhoneNumber(this.phoneNumber)){
        //    alert("请输入正确的手机号码")
        this.asyncShowToast({
                isShow:true,
                msg:"请输入正确的手机号码",
                type:"error"
            })
        return;
        }
        // 校验滑块验证码
        if(this.msg=='再试一次' || this.msg=='向右滑动'){
            // alert("请滑动滑块验证码")
             this.asyncShowToast({
                isShow:true,
                msg:"请滑动滑块验证码",
                type:"error"
            })
            return;
        }
        return true;
    },
    // 获取验证码
     async getCode(){
        // 校验手机号码格式
        // let reg=/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
        // console.log(reg.test(this.phoneNumber));
        // if(!reg.test(this.phoneNumber)){
        //     alert("请输入正确的手机号码")
        //     return;
        // }
        // if(!validatePhoneNumber(this.phoneNumber)){
        //    alert("请输入正确的手机号码")
        // return;
        // }
        // // 校验滑块验证码
        // if(this.msg=='再试一次' || this.msg=='向右滑动'){
        //     alert("请滑动滑块验证码")
        //     return;
        // }
          // 校验手机号码格式和滑块验证码
        if(!this.toVerify()) return;
        // 获取验证码
        let res = await SendSMSAPI({
            phone:this.phoneNumber
        })

        console.log("res",res); 

        if(!res)return;

        if(res.code==0){
        this.isShowCount = true
        // 获取验证码的倒计时
        let timer = setInterval(()=>{
            this.count--;
            if(this.count==0){
                clearInterval(timer);
                this.count=6;
                this.isShowCount=false;
            }
        },1000)
        }
      
    },
    //登录
  async submitFn(){
        // let flag =this.toVerify();
        // console.log("flag",flag);
        // if(!flag) return; 
        if(!this.toVerify()) return;
        // alert("登陆成功")
        // 验证短信验证码
        if(!this.dxcode.trim()){
            // alert("请输入短信验证码")
            this.asyncShowToast({
                isShow:true,
                msg:"请输入短信验证码",
                type:"error"
            })
            return
        }
        let uuid = localStorage.getItem("uuid");
        console.log("uuid:",uuid);
        let res = null;
        if(uuid){
            res = await BindingAPI({
            verifyCode:this.dxcode,
            phone:this.phoneNumber,
            uuid,
            })
            console.log("准备发请求");
        }else{
            console.log("普通手机号码登录请求");
        // 发起手机号码登录请求
         res = await PhoneReginAPI({
            verifyCode:this.dxcode,
            phone:this.phoneNumber
        });
        }
      
        console.log("1111",res);
        if(!res) return;
        // 1.提示
        // alert("登陆成功!");
         this.asyncShowToast({
                isShow:true,
                msg:"登陆成功!",
                type:"success"
            })
        // 2.隐藏登陆框
        this.changeIsShowLoginModal(false);
        // 3.存储token
        localStorage.setItem("x-auth-token",res["x-auth-token"])
        // 4.切换按钮(显示购物车按钮)
          this.changeIsLogined(true);
          if(uuid){
            localStorage.removeItem("uuid");
          }
        // uuid && localStorage.removeItem("uuid");
        // 登陆成功后获取用户信息
        // let userres = await UserProfilesAPI()
        // console.log("获取用户信息",userres);
        // 优化后,直接请求actions
        this.asyncChangeUserInfo();
    },
    showQrFn(){
        this.isShowLogin=false;
        //获取二维码 并展示
          // 申请微信登录二维码
        //   实例化js
          let _this = this;
          new WxLogin({
            id: "weixin",
            appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
            scope: "snsapi_login",
            // 扫码成功后重定向的接口
            redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
            // state填写编码后的url
            state: encodeURIComponent(
              window.btoa("http://127.0.0.1:8080" + _this.$route.path)
            ),
            // 调用样式文件
            href: "data:text/css;base64,LmltcG93ZXJCb3ggLnRpdGxlLA0KLmltcG93ZXJCb3ggLmluZm8gew0KICAgIGRpc3BsYXk6IG5vbmU7DQp9",
          });
        
    }
  },
}

</script>

<style lang="less" scoped>
.loginbox{
    width: 100%;
    height: 100%;
    position: fixed;
    left: 0;
    top: 0;
    .mask{
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.5)
    }
    .login{
        position: absolute;
        top: 0;
        right: 0;
        left: 0;
        bottom: 0;
        margin: auto;
        width: 555px;
        height: 423px;
        background: url("../assets/img/login-box-bg.png");
        .close{
            position: absolute;
            right: 60px;
            top: 15px;
            width: 22px;
            height: 22px;
            background: url("../assets/img/close.png");
        }
        section{
            line-height: 40px;
            text-align: center;
            padding-top: 40px;
            a{
                text-decoration: none;
                color: #000;
                &.active{
                    color: red;
                }
            }
        }
        .content{
            width: 350px;
            margin: 0 auto;
            text-align: center;
           .phonelogin{
            margin-top: 20px;
            .row{
                display: flex;
                margin-bottom: 20px;
                input{
                    flex:1;
                    height: 45px;
                    text-indent: 1em;
                }
                .btn{
                    background: #0a328e;
                    color: #fff;
                    border: none;
                    cursor: pointer;
                }
                .btncode{
                    margin-left: 10px;
                    width: 80px;
                }
                .btnlogin{
                    width: 100%;
                    height: 45px;
                }
            }
           }
        }
    }
}
/deep/.slide-box {
    width: 100%;
    position: relative;
    box-sizing: border-box;
    canvas {
        position: absolute;
        left: 0;
        top: -120px;
        display: none;
        width: 100%;
        box-sizing: border-box;
    }
    .slide-verify-block{
        width: 85px;
        height: 136px;
    }
    .slide-verify-refresh-icon {
        top: -120px;
        display: none;
    }
    &:hover {
        canvas {
            display: block;
        }
        .slide-verify-refresh-icon {
            display: block;
        }
    }
}
</style>